package cn.hsa.fqz.task.service.impl;

import cn.hsa.fqz.task.controller.vo.TTaskWorkReportDetailVO;
import cn.hsa.fqz.task.controller.vo.TTaskWorkReportQueryVO;
import cn.hsa.fqz.task.dao.TTaskWorkReportDetailAttachmentMapper;
import cn.hsa.fqz.task.dao.TTaskWorkReportDetailMapper;
import cn.hsa.fqz.task.dao.TTaskWorkReportMapper;
import cn.hsa.fqz.task.entity.*;
import cn.hsa.fqz.task.service.RegionService;
import cn.hsa.fqz.task.service.TSysFileService;
import cn.hsa.fqz.task.service.TaskReportService;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import cn.hsa.fqz.task.service.dto.TTaskWorkReportDetailDTO;
import cn.hsa.hsaf.core.framework.util.PageResult;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description TODO
 * @ClassName TaskReportServiceImpl
 * @Author Liu.Jun
 * @Create 2023-12-11 11:17
 * @Version 1.0.0
 */
@Slf4j
@Service
public class TaskReportServiceImpl implements TaskReportService {

    @Autowired
    private TTaskWorkReportMapper tTaskWorkReportMapper;

    @Autowired
    private TTaskWorkReportDetailMapper tTaskWorkReportDetailMapper;

    @Autowired
    private TTaskWorkReportDetailAttachmentMapper tTaskWorkReportDetailAttachmentMapper;

    @Autowired
    private RegionService regionService;

    @Autowired
    private TSysFileService fileService;

    @Override
    public List<TTaskWorkReport> getReportByYearmutil(String yearmutil) {
        return tTaskWorkReportMapper.selectByYears(yearmutil);
    }

    @Override
    public PageResult<TTaskWorkReportDetailDTO> getPageDetailByCondition(TTaskWorkReportQueryVO query) {
        Date startTime = null, endTime = null;
        if (Objects.nonNull(query.getCondition())) {
            if (!ArrayUtils.isEmpty(query.getCondition().getTimes())) {
                String start = query.getCondition().getTimes()[0];
                String end = query.getCondition().getTimes()[1];

                if (!org.apache.commons.lang.StringUtils.isBlank(start)) {
                    startTime = DateUtil.beginOfDay(DateUtil.parseDate(start));
                }
                if (!org.apache.commons.lang.StringUtils.isBlank(end)) {
                    endTime = DateUtil.beginOfDay(DateUtil.parseDate(end));
                }
            }
        }
        Page<TTaskWorkReportDetail> page =  PageHelper.startPage(query.getPage().getPageNum(), query.getPage().getPageSize());
        List<TTaskWorkReportDetail> list = tTaskWorkReportDetailMapper.getDetailsPageByCondition(query.getCondition(),startTime, endTime);
        List<RegionDO>  regionList = regionService.getRegionsBypRegion("999");
        List<TTaskWorkReportDetailDTO> result = transformDetailsDTO(list,regionList);
        PageResult<TTaskWorkReportDetailDTO> pageResult = new PageResult<>();
        pageResult.setData(result);
        pageResult.setPageNum(page.getPageNum());
        pageResult.setPageSize(page.getPageSize());
        pageResult.setPages(page.getPages());
        pageResult.setRecordCounts((int)page.getTotal());
        return pageResult;
    }

    private List<TTaskWorkReportDetailDTO> transformDetailsDTO(List<TTaskWorkReportDetail> list, List<RegionDO> regionList) {
        List<TTaskWorkReportDetailDTO> dtos = Lists.newArrayList();
        for (TTaskWorkReportDetail detail:list) {
            TTaskWorkReportDetailDTO dto = new TTaskWorkReportDetailDTO();
            BeanUtils.copyProperties(detail, dto);
            Optional<RegionDO> optional = regionList.stream().filter(e -> e.getRegion().intValue() == Integer.valueOf(detail.getRegion()).intValue()).findFirst();
            if(optional.isPresent()){
                dto.setRegionName(optional.get().getProvice());
            }
            List<TTaskWorkReportDetailAttachment> attachments = tTaskWorkReportDetailAttachmentMapper.selectByRptDetailId(detail.getId());
            dto.setAttachments(attachments);
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public Boolean addRptDetail(TTaskWorkReportDetailVO vo) {
        TTaskWorkReportDetail po = new TTaskWorkReportDetail();
        BeanUtils.copyProperties(vo,po);
        tTaskWorkReportDetailMapper.insertSelective(po);
        List<String> attachments = vo.getAttachments();
        if(CollectionUtil.isNotEmpty(attachments)){
            for (String attachment:attachments) {
                LambdaQueryWrapper<TSysFileDO>
                        wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSysFileDO::getFileNo, attachment);
                List<TSysFileDO> result = fileService.list(wrapper);
                if(CollectionUtil.isNotEmpty(result)){
                    TTaskWorkReportDetailAttachment attachmentDO = new TTaskWorkReportDetailAttachment();
                    attachmentDO.setReportId(vo.getReportId());
                    attachmentDO.setDetailId(po.getId());
                    attachmentDO.setFileNo(attachment);
                    attachmentDO.setFileName(result.get(0).getFileName());
                    tTaskWorkReportDetailAttachmentMapper.insertSelective(attachmentDO);
                }
            }
        }
        return true;
    }

    @Override
    public WrapperResponse<Boolean> deleteRptDetail(LoginUserDTO dto, Integer reportDetailId) {
        TTaskWorkReportDetail detail = tTaskWorkReportDetailMapper.selectByPrimaryKey(reportDetailId);
        if(!detail.getCreateBy().equals(dto.getUid())){
            return WrapperResponse.error(-1,"此数据不是当前用户创建，不能删除",null);
        }
        tTaskWorkReportDetailAttachmentMapper.deleteByDetailId(reportDetailId);
        tTaskWorkReportDetailMapper.deleteByPrimaryKey(reportDetailId);
        return WrapperResponse.success(true);
    }

    @Override
    public TTaskWorkReportDetailAttachment getAttachmentByDetailAndFileNo(String fileNo, Integer detailId) {
        return tTaskWorkReportDetailAttachmentMapper.getAttachmentByDetailAndFileNo(fileNo,detailId);
    }
}
